﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ComponentSample
{
    public partial class AnswerComponent : Component
    {
        AsyncFunc<string, string> getAnswer;

        public AnswerComponent()
        {
            InitializeAsyncFunc();
            InitializeComponent();
        }

        public AnswerComponent(IContainer container)
        {
            container.Add(this);
            InitializeAsyncFunc();
            InitializeComponent();
        }

        private void InitializeAsyncFunc()
        {
            getAnswer = new AsyncFunc<string, string>(GetAnswer);
        }

        public void GetAnswerAsync(string question)
        {
               getAnswer.TryInvokeAsync(question);
        }

        public void CancelAsync()
        {
            getAnswer.Cancel();
        }

        public event AsyncFuncCompletedEventHandler<string> GetAnswerCompleted
        {
            add { getAnswer.Completed += value; }
            remove { getAnswer.Completed -= value; }
        }

        public event ProgressChangedEventHandler ProgressChanged
        {
            add { getAnswer.ProgressChanged += value; }
            remove { getAnswer.ProgressChanged -= value; }
        }

        // Extremely complex stuff
        private string GetAnswer(string question, Func<bool> isCancelled, Action<int> reportProgress)
        {
            for (int i = 0; i < 100; i++)
            {
                if (isCancelled()) return null;
                reportProgress(i);
                System.Threading.Thread.Sleep(50);
            }
            return "42";
        }
    }
}
